package roborally.util;

import java.io.*;
import roborally.Pieces.*;
/**
 * This is a class with static methods to save and load a program.

 * @version 3.0
 * @author Bart Opsomer 2de Bachelor Ingenieurswetenschappen Electrotechniek-Computerwetenschappen 
 * 		   Peter Opsomer 1ste Master Wiskundige IngenieursTechnieken
 */
public class Program {
    /**
     * saves the program as a .txt-file at the given location
     * @param filename the name of the file to save to
     * @throws	Exception 
     * 			when the save was not successful
     */
    public static void saveProgram(String filename, String wholeProgram) throws Exception
    {
    	Writer output = null;
    	try{
    		output = new BufferedWriter(new FileWriter(new File(filename)));
      	  	output.write(wholeProgram);
    	}
        finally {
            output.close();
            // if this reached, only then successful save
        }
    }
    /**
     * Return a new CommandParser for the given Robot with the the program of the given filename
     */
    public static CommandParser loadProgramForRobot(Robot robot, String filename) throws Exception {
    	return new CommandParser(loadProgram(filename),robot );
    }
    /**
     * Return a new CommandParser for the given Robot with the given program
     */
    public static CommandParser makeProgramForRobot(Robot robot, String wholeProgram) {
    	return new CommandParser(wholeProgram,robot );
    }
    /**
     * Return the Program in the text-file with the given name. The program still needs to be initialized with a Robot.
     * 
     * @param filename the name of the file to open
     * @throws	Exception
     * 			when load was not successful
     */
    public static String loadProgram(String filename) throws Exception {
    	StringBuilder contents = new StringBuilder();
    	BufferedReader input =  new BufferedReader(new FileReader(new File(filename) ) );
    	try {
    		String line = null;
    		// build the String of the program
    		while (( line = input.readLine()) != null){
    			contents.append(line);
    			contents.append(System.getProperty("line.separator"));
    		}
    	}
    	finally {
    		input.close();
    	}
        
        String toParse = contents.toString().trim();
        String program = "";
        for(int i = 0; i < toParse.length(); i ++) {
        	String charString = toParse.charAt(i) + "";
        	if(charString.matches("[a-zA-Z_0-9]") || charString.equals("(") ||charString.equals(" ") ||
        			charString.equals(")") ||charString.equals("-") || charString.equals("	") ) {
        		program = program + charString;
        	}
        }
        
        return program;
    }
}
